package controllers

import (
	"encoding/json"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"github.com/kataras/iris/sessions"
	"html/template"
	"iris-shop/common/db/rabbitmq"
	datamodels "iris-shop/common/models"
	"iris-shop/common/services"
	"os"
	"path/filepath"

	"strconv"
)

type ProductController struct {
	Ctx            iris.Context
	ProductService services.IProductService
	OrderService   services.IOrderService
	Rabbitmq 	   *rabbitmq.RabbitMQ
	Session        *sessions.Session
}

var (
	htmlOutPath = "./app/fronted/web/htmlProductShow/" //静态文件目录
	templatePath = "./app/fronted/web/views/template/" //模板目录
)

func exist(filename string) bool {
	_, err := os.Stat(filename);
	if err == nil && os.IsExist(err) {
		return true
	}
	return false
}

func (p *ProductController) GetGenerateHtml() {
	productString := p.Ctx.URLParam("productID")
	productID, err := strconv.Atoi(productString)
	if err != nil {
		p.Ctx.Application().Logger().Debug(err)
	}
	contentTmp, err := template.ParseFiles(filepath.Join(templatePath,"product.html"))
	if err != nil {
		p.Ctx.Application().Logger().Error(err)
	}

	filename := filepath.Join(htmlOutPath,"htmlProduct.html")

	product, err := p.ProductService.GetProductByID(int64(productID))
	if err != nil {
		p.Ctx.Application().Logger().Error(err)
	}

	generatedStaticHtml(p.Ctx, contentTmp,filename, product)

}

func generatedStaticHtml(ctx iris.Context, template *template.Template, fileName string, product *datamodels.Product) {
	if exist(fileName) {
		err := os.Remove(fileName)
		if err != nil {
			ctx.Application().Logger().Error(err)
		}
	}

	file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, os.ModePerm)
	if err != nil {
		ctx.Application().Logger().Error(err)
	}
	defer file.Close()
	_ = template.Execute(file, &product)
}


func (p *ProductController) GetDetail() mvc.View {
	product, err := p.ProductService.GetProductByID(1)
	if err != nil {
		p.Ctx.Application().Logger().Error(err)
	}

	return mvc.View{
		Layout: "shared/productLayout.html",
		Name:   "product/view.html",
		Data: iris.Map{
			"product": product,
		},
	}
}

func (p *ProductController) GetOrder() []byte {
	productString := p.Ctx.URLParam("productID")
	userString := p.Ctx.GetCookie("uid")
	productID, err := strconv.ParseInt(productString,10,64)
	if err != nil {
		p.Ctx.Application().Logger().Debug(err)
	}

	userID, err := strconv.ParseInt(userString, 10, 64)
	if err != nil {
		p.Ctx.Application().Logger().Debug(err)
	}

	//rabbitmq版本

	message := datamodels.NewMessage(userID, productID)
	byteMessage, err := json.Marshal(message)
	if err != nil {
		p.Ctx.Application().Logger().Debug(err)
	}

	err = p.Rabbitmq.PublishSimple(string(byteMessage))
	if err != nil {
		p.Ctx.Application().Logger().Debug(err)
	}

	return []byte("true")





	/*
	普通的商品抢购
	product, err := p.ProductService.GetProductByID(int64(productID))
	p.Ctx.Application().Logger().Debug(product)
	if err != nil {
		p.Ctx.Application().Logger().Debug(err)
	}
	var orderID int64
	showMessage := "抢购失败！"
	//判断商品数量是否满足需求
	p.Ctx.Application().Logger().Debug(product.ProductNum)
	if product.ProductNum > 0 {
		//扣除商品数量
		product.ProductNum -= 1
		err := p.ProductService.UpdateProduct(product)
		if err != nil {
			p.Ctx.Application().Logger().Debug(err)
		}
		//创建订单
		userID, err := strconv.Atoi(userString)
		if err != nil {
			p.Ctx.Application().Logger().Debug(err)
		}

		order := &datamodels.Order{
			UserId:      int64(userID),
			ProductId:   int64(productID),
			OrderStatus: datamodels.OrderSuccess,
		}
		//新建订单
		orderID, err = p.OrderService.InsertOrder(order)
		if err != nil {
			p.Ctx.Application().Logger().Debug(err.Error())
		} else {
			showMessage = "抢购成功！"
		}
	}
	 */

	//return mvc.View{
	//	Layout: "shared/productLayout.html",
	//	Name:   "product/result.html",
	//	Data: iris.Map{
	//		"orderID":     orderID,
	//		"showMessage": showMessage,
	//	},
	//}

}
